<?php

namespace app\technician\controller;

use app\common\controller\Api;
use app\common\model\HandCard;
use app\common\model\HandCard as HandCardM;
use app\common\model\Wait;
use think\Db;
use Carbon\Carbon;
use think\Exception;

/**
 * 下单控制器
 * @package app\index\controller
 */
class Order extends Home
{
    public $noNeedLogin = [];
    /**
     * 副项下单
     */
    public function otherAdd(){
        if($this->request->isPost()){
            $userInfo = $this->userInfo;
            $getData= $this->request->post();
            $validate = new \app\web\validate\Order();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $totalNum = $getData['man_num'] + $getData['woman_num'] + $getData['other_num'];
            if( $getData['order_type'] == '1' && $totalNum <= 0){
                $this->result('请至少选择一个技师', '', 204);
            }
            $projectName = Db::name('qt_project')->where('id',$getData['project_id'])->value('name');
            //不自动排钟
            if(($getData['order_type'] == '1' && $this->storeInfo['is_auto_queue'] == '0') || $getData['time_type'] == '2'){
                if( empty($getData['man_num'])){
                    $getData['man_num'] = 0;
                }else{
                    $sex = '1';
                    $number = $getData['man_num'];
                    Wait::setWait($getData,$this->storeInfo,$projectName,$sex,$number,$this->userInfo);
                }
                if( empty($getData['woman_num'])){
                    $getData['woman_num'] = 0;
                }else{
                    $sex = '2';
                    $number = $getData['woman_num'];
                    Wait::setWait($getData,$this->storeInfo,$projectName,$sex,$number,$this->userInfo);
                }
                if( empty($getData['other_num'])){
                    $getData['other_num'] = 0;
                }else{
                    $sex = '3';
                    $number = $getData['other_num'];
                    Wait::setWait($getData,$this->storeInfo,$projectName,$sex,$number,$this->userInfo);
                }
                $this->result('添加成功', '', 200);
            }
            //房间床位数限制
            $roomNumber = Db::name('qt_room')->where(['id'=>$getData['room_id']])->value('bed_num');
            $roomUseOrder = Db::name('qt_order')->where(['room_id'=>$getData['room_id'],'pay_status'=>'1'])->find();
            $usedNumber = 0;
            $totalNum = $getData['man_num'] + $getData['woman_num'] + $getData['other_num'];
            if(!empty($roomUseOrder)){
                $usedNumber = Db::name('qt_order_project')
                    ->whereNotNull('engineer_id')
                    ->where(['order_id'=>$roomUseOrder['id'],'is_change'=>'1','is_add'=>'1'])
                    ->where('status','<','3')
                    ->where('is_delete',2)
                    ->count();
            }
            if($getData['order_type'] == '1'){
                //判断当前房间内未结账的项目数
                if(($usedNumber + $totalNum) > $roomNumber){
                    $this->result('超出房间床位数','',204);
                }
            }else{
                if(($usedNumber + 1) > $roomNumber ){
                    $this->result('超出房间床位数','',204);
                }
            }
            $getData['creater_room'] = Db::name('qt_room_log')
                ->where(['room_id'=>$getData['room_id']])
                ->order('id desc')
                ->value('user_id');
            if ($this->storeInfo['floor_commission_type'] == '1') {
                $getData['sale_id'] = $userInfo['id'];
            } else {
                $getData['sale_id'] = $getData['creater_room'];
            }
            $getData['delay'] = 0;
            $getData['time_type'] = 1;
            $getData['create_id'] = $userInfo['id'];
            $orderModel = new \app\common\model\Order();
            $code = $orderModel->create_order($getData,$userInfo);
            if($code['code'] == '200'){
                Db::name('qt_room')->where(['id'=>$getData['room_id']])->update(['retreat_time'=>null]);
                $this->result('下单成功','',200);
            }
        }else{
            $this->result('无效的请求','',204);
        }
    }


    /**
     * 会做项目的空闲技师
     */
    public function engineerEmpty()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_user_project')
                ->field('p.id,u.work_number,u.work_status')
                ->alias('p')
                ->leftJoin('qt_users u', 'u.id = p.engineer_id')
                ->where('p.project_id', $getData['project_id'])
                ->where(['u.work_status' => '1','u.status'=>'0'])
                ->select();
            $this->result('查询成功', $data, 200);

        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 更换手牌
     */
    public function changeHandCard(){

        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post['type'] = 1;//只有项目
            if (empty($post['hand_card_name']) || empty($post['order_id']) || empty($post['type'])) {
                $this->result('缺少参数', '', 204);
            }

            if($post['type'] == '1'){//1项目 2商品
                $order_data = Db::name('qt_order_project')->where(['id'=>$post['order_id']])->find();
            }else{
                $order_data = Db::name('qt_product_order_item')->where(['id'=>$post['order_id']])->find();
            }
            if (empty($order_data)) $this->result('单据数据异常', '', 204);

            $new_hand_card_data = Db::name('qt_hand_card')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('name', $post['hand_card_name'])
                ->find();
            if (empty($new_hand_card_data)) $this->result('没有找到新手牌'.$post['hand_card_name'] .'号','',204);


            //检测最大消费金额
            $checkMoney = HandCard::checkMaxMoney($new_hand_card_data['id'],$order_data['price']);
            if($checkMoney == false){
                $this->result('手牌超出最大消费', '', 204);
            }
            //检测停牌
            $checkStatus = HandCard::checkStatus($new_hand_card_data['id']);
            if($checkStatus == false) $this->result('新手牌未发放', '', 204);

            //判断新手牌是否发放,如果手牌使用了不能发放
            $new_hand_grant_data = Db::name('qt_hand_grant')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('hand_card_id', $new_hand_card_data['id'])
                ->where('status',2)
                ->find();
            if (empty($new_hand_grant_data)) $this->result('新手牌未发放','',204);

            //更新新房间信息
            Db::startTrans();
            try {

                //更新项目
                if($post['type'] == '1'){//1项目 2商品
                    Db::name('qt_order_project')
                        ->where(['id' => $post['order_id']])
                        ->update(['hand_card_id' => $new_hand_card_data['id'], 'old_card_id' => $order_data['hand_card_id']]);

                    //老手牌減少金额
                    HandCardM::decHandCardMoney($post['order_id'],$order_data['hand_card_id'],'1');
                    //新手牌增加金额
                    HandCardM::incHandCardMoney($post['order_id'],$new_hand_card_data['id'],'1');

                } else {    //更新商品
                    Db::name('qt_product_order_item')
                        ->where(['id' =>$post['order_id']])
                        ->update(['hand_card_id' => $new_hand_card_data['id'], 'old_card_id' => $order_data['hand_card_id']]);

                    //老手牌減少金额
                    HandCardM::decHandCardMoney($post['order_id'],$order_data['hand_card_id'],'2');
                    //新手牌增加金额
                    HandCardM::incHandCardMoney($post['order_id'],$new_hand_card_data['id'],'2');
                }

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转手牌失败', '', 204);
            }

            $this->result('转手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);

    }


}
